<template>
    <div class="page-wrapper">
        <el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
            <el-form-item>
                <el-button type="primary" @click="addOrUpdateHandle({})" v-if="hasRule('admin/inventory/out/add')">新建出库单</el-button>
            </el-form-item>
            <el-form-item>
                <el-date-picker :shortcuts="SHORTCUTS" v-model="record_time" style="width:240px;" @change="dataChange" type="daterange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" clearable />
            </el-form-item>
            <el-form-item>
                <el-input v-model="state.queryForm.contents" placeholder="输入产品名称搜索" clearable style="width: 200px"></el-input>
            </el-form-item>
            <el-form-item>
                <el-select
                    v-model="state.queryForm.out_type"
                    clearable
                    placeholder="选择出库类型"
                    style="width: 150px"
                >
                    <el-option label="生产出库" :value="1" />
                    <el-option label="销售出库" :value="2" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-input v-model="state.queryForm.customer_name" placeholder="输入客户搜索" clearable style="width: 150px"></el-input>
            </el-form-item>
            <el-form-item>
                <el-input v-model="state.queryForm.department_name" placeholder="输入部门搜索" clearable style="width: 150px"></el-input>
            </el-form-item>
            <!-- <el-form-item>
                <el-input v-model="state.queryForm.company_manager" placeholder="归属人" clearable style="width: 150px"></el-input>
            </el-form-item>
            <el-form-item>
                <el-input v-model="state.queryForm.submitter" placeholder="提交人" clearable style="width: 150px"></el-input>
            </el-form-item>
            <el-form-item>
                <el-select v-model="state.queryForm.checked" value-key="" placeholder="状态" clearable style="width: 150px">
                    <el-option label="待审核" value="3"></el-option>
                    <el-option label="已确认" value="4"></el-option>
                </el-select>
            </el-form-item> -->
            <el-form-item>
                <el-button @click="getDataList()" type="primary">查询</el-button>
                <el-button @click="resetForm()">重置</el-button>
            </el-form-item>
			<el-form-item>
				<el-button @click="exportData()" type="success" v-if="hasRule('admin/inventory/out/export')">导出</el-button>
			</el-form-item>
        </el-form>
			<!-- <div>
				<el-button type="primary" v-if="hasRule('admin/inventory/out/add')" @click="handleExport" :loading="loading">导出</el-button>
			</div> -->
		<el-table v-loading="state.dataListLoading" :data="dataList" border style="width: 100%" width="100%" height="100%" @selection-change="selectionChangeHandle" @row-dblclick="rowDblclick">
			<!-- <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column> -->
			<!-- <el-table-column prop="id" label="单号" header-align="center" align="center"></el-table-column> -->
			<el-table-column prop="order_sn" label="出库单号" header-align="center" align="center"></el-table-column>
			<!-- <el-table-column prop="status" label="出库类型" header-align="center" align="center">
				<template #default="scope">
					<span v-if="scope.row.is_fee == 3" class="status2">退款审核中</span>
					<span v-if="scope.row.is_fee == 4" class="status3">已退款</span>
				</template>
			</el-table-column> -->
			<el-table-column prop="out_time" label="出库时间" header-align="center" align="center"></el-table-column>
			<el-table-column prop="out_type" label="出库类型" header-align="center" align="center">
                <template #default="scope">
					<span v-if="scope.row.out_type == 1">生产出库</span>
					<span v-if="scope.row.out_type == 2">销售出库</span>
				</template>
            </el-table-column>
			<el-table-column prop="status" label="出库状态" header-align="center" align="center">
                <template #default="scope">
					<span v-if="scope.row.status == 1" class="status2">草稿</span>
					<span v-if="scope.row.status == 2" class="status3">已出库</span>
				</template>
            </el-table-column>
			<el-table-column prop="detail" label="出库产品" header-align="center" align="center" width="150">
                <template #default="scope">
                    <el-tooltip
                        placement="top"
                        :content="scope.row.detailInfo"
                        raw-content
                    >
                        <div class="w100 text-cut">
                            <span v-if="scope.row.contents.length">{{ scope.row.contents[0].productName }}</span>
                        </div>
                    </el-tooltip>
				</template>
            </el-table-column>
			<el-table-column prop="customer_name" label="客户名称" header-align="center" align="center" show-overflow-tooltip></el-table-column>
			<el-table-column prop="department_name" label="部门名称" header-align="center" align="center" show-overflow-tooltip></el-table-column>
			<el-table-column prop="remark" label="出库备注" header-align="center" align="center" show-overflow-tooltip width="100"></el-table-column>
			<el-table-column prop="operator" label="最后操作人" header-align="center" align="center"></el-table-column>
			<el-table-column prop="updated_at" label="最后修改时间" header-align="center" align="center"></el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="200">
				<template #default="scope">
					<el-button type="primary" link @click="addOrUpdateHandle(scope.row, true)" v-if="hasRule('admin/inventory/out/detail')">查看</el-button>
					<el-button type="primary" link @click="addOrUpdateHandle(scope.row)" v-if="hasRule('admin/inventory/out/update') && scope.row.status == 1">编辑</el-button>
					<el-button type="danger" link @click="deleteHandle(scope.row.id)" v-if="hasRule('admin/inventory/out/delete') && scope.row.status == 1">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.page"
			:page-sizes="state.pageSizes"
			:page-size="state.per_page"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
		<!-- 弹窗, 新增 / 修改 -->
		<add-or-update ref="addOrUpdateRef" @refreshDataList="getDataList"></add-or-update>
	</div>
</template>

<script setup lang="ts">
import { useCrud } from '@/hooks'
import { reactive, ref, computed } from 'vue'
import store from '@/store'
import { IHooksOptions } from '@/hooks/interface'
import { ElMessageBox, ElMessage } from 'element-plus'
import { hasRule, downMethod, timeResetDate } from '@/utils/tool'
import { exportinventory, postApi, addInventory } from '@/api/api'
import { SHORTCUTS } from '@/config'
import AddOrUpdate from './add-or-update.vue'
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';
import { elMsg } from '@/utils/message';

const prop = defineProps({
	scrollTop:{
		type: Number,
		default: 0
	}
})
const emit = defineEmits(['setScroll'])
let scrollTopData = 0;
const state: IHooksOptions = reactive({
	dataListUrl: '/api/strator/inventory/list',
	deleteUrl: '/api/strator/inventory/delete',
	queryForm: {
        type: 2,
		contents: '',
		customer_name: '',
		department_name: '',
		out_type: '',
		is_sale: 1,
		start: '',
		end: '',
	}
})
const record_time = ref([])
// 选择时间范围
const dataChange = (e: any) => {
	if(e){
		state.queryForm.start = e[0] + ' 00:00:00'
		state.queryForm.end = e[1] + ' 23:59:59'
	}else{
		state.queryForm.start = ''
		state.queryForm.end = ''
	}
};
// 计算列宽自适应逻辑
const fitToColumn = (data) => {
  const colWidths = [];
  // 遍历表头和数据内容，计算每列最大宽度
  data.forEach(row => {
    Object.values(row).forEach((value, colIndex) => {
      const length = value ? value.toString().length : 0;
      // 中文占双倍宽度（根据字符类型动态调整）
      const chineseMultiplier = /[\u4e00-\u9fa5]/.test(value) ? 2 : 1;
      const cellWidth = Math.ceil(length * chineseMultiplier * 1.2); // 增加 20% 余量
      if (!colWidths[colIndex] || cellWidth > colWidths[colIndex]) {
        colWidths[colIndex] = cellWidth;
      }
    });
  });
  // 转换为 xlsx 的列宽格式
  return colWidths.map(wch => ({ wch }));
}
const exportData = () => {
    exportinventory(state.queryForm).then((result) => {
        const header = JSON.parse(result.data.header);
        console.log(header);
        exportExcel([JSON.parse(result.data.header),...result.data.list], Object.keys(header), result.data.filename)
    }).catch((err) => {
        console.log(err);
    });
}
const exportExcel = (data, header, fileName = 'data.xlsx') => {
  const worksheet = XLSX.utils.json_to_sheet(data, {header:header, skipHeader:true});
  worksheet['!cols'] = fitToColumn(data); // 设置列宽
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
  saveAs(blob, fileName);
}
const addOrUpdateRef = ref()
const dataList = computed(() => {
	state.dataList?.forEach((item: any) => {
        if (item.contents) {
            item.contents = JSON.parse(item.contents);
            item.detailInfo = "";
            let toa = 0;
            item.contents.forEach(tem => {
                toa += Number(tem.quantity)
                item.detailInfo += `
                    <div class="flex flexB"><span class="mr20">${tem.productName}(${tem.product_attr})</span><span style="width: ${tem.batchNo?'200px':'100px'}">出库数量${tem.batchNo?'('+tem.batchNo+')':''}：${tem.quantity}</span></div>
                `
            })
            item.detailInfo += `<div style="text-align: right">出库总数：${Number((toa).toFixed(2))}</div>`
        } else {
            item.detailInfo = "";
        }
	})
	return state.dataList
})
const addOrUpdateHandle = (row: any, isView?: any) => {
	addOrUpdateRef.value.init(row.id,2, isView)
}
const loading = ref(false)
const handleExport = () => {
	let data = {
		...state.queryForm,
		export: '1'
	}
	let ajaxData: any = {
		params:data,
		method:'POST',
		url:'/api/shop/in_store/list',
		fileType:'xlsx',
		fileName:'出库单' + timeResetDate()
	}
	loading.value = true
	downMethod(ajaxData).then((res: any) => {
		loading.value = false
		if(res){
			ElMessage.success({
				message: '导出成功',
				duration: 1500,
			})
		} else {
			ElMessage.error('导出失败，请重试')
		}
	}).catch((err: any) => {
		loading.value = false
		ElMessage.error('导出失败，请重试')
		// .console.log(err)
	})
}
const handleDel = (id: number) => {
	ElMessageBox.confirm('确认删除吗？', '操作提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		closeOnClickModal: false,
		customClass: 'receiptConfirm',
		center: true
	})
		.then(({ value }) => {
			postApi('/api/shop/in_store/delete', {
				id:id,
			}).then((res: any) => {
				if(res.code == 200){
					ElMessage.success({
						message: '删除成功',
						duration: 1200,
					})
					getDataList()
				} else {
					ElMessage.error(res.message || res.data || '操作失败，请重试')
				}
			}).catch((err: any) => {
				// .console.log(err)
			})
		})
		.catch(() => {})
}
const resetForm = () => {
	record_time.value = []
	state.queryForm.contents = ''
	state.queryForm.customer_name = ''
	state.queryForm.department_name = ''
	state.queryForm.out_type = ''
	state.queryForm.is_sale = 1
	state.queryForm.start = ''
	state.queryForm.end = ''
	getDataList()
}
const rowDblclick = (row,col) => {
    if(col.property == 'remark'){
        ElMessageBox.prompt('请输入备注', '修改备注', {
            confirmButtonText: '提交',
            cancelButtonText: '关闭',
            inputValue: row.remark
        })
            .then(({ value }) => {
                addInventory({
                    id: row.id,
                    remark: value
                }).then((result) => {
                    elMsg('已提交', 'success')
                    currentChangeHandle(state.page)
                }).catch((err) => {
                    
                });
            })
            .catch(() => {
            // .
        })
    }
}
// getProductSkuAll().then((result) => {
//     console.log(result);
// }).catch((err) => {
    
// });
const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteHandle } = useCrud(state)
</script>
<style lang="scss" scoped>
.receivable {
	:deep() {
		.el-tabs__header {
			margin: 0 0 5px;
		}
	}
}
</style>
